#include "stdafx.h"
#include "CropImage.h"
// #include "cv2tiff.h"



/* $Id: raw2tiff.c,v 1.23 2006/03/23 14:54:02 dron Exp $
 *
 * Project:  libtiff tools
 * Purpose:  Convert raw byte sequences in TIFF images
 * Author:   Andrey Kiselev, dron@ak4719.spb.edu
 *
 ******************************************************************************
 * Copyright (c) 2002, Andrey Kiselev <dron@ak4719.spb.edu>
 *
 * Permission to use, copy, modify, distribute, and sell this software and 
 * its documentation for any purpose is hereby granted without fee, provided
 * that (i) the above copyright notices and this permission notice appear in
 * all copies of the software and related documentation, and (ii) the names of
 * Sam Leffler and Silicon Graphics may not be used in any advertising or
 * publicity relating to the software without the specific, prior written
 * permission of Sam Leffler and Silicon Graphics.
 * 
 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
 * 
 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
 * OF THIS SOFTWARE.
 */
#include "stdarg.h"
#include "tiffconf.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <math.h>
#include <ctype.h>

#ifdef HAVE_UNISTD_H
//# include <unistd.h>
#endif

#if HAVE_FCNTL_H
# include <fcntl.h>
#endif

#if HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif

#if HAVE_IO_H
# include <io.h>
#endif

extern "C" {
#include <tiffio.h>
}


// OpenCV
#include <cv.h>
#include <cv.hpp>


#ifndef HAVE_GETOPT
extern int getopt(int, char**, char*);
#endif

#ifndef O_BINARY
# define O_BINARY 0
#endif

typedef enum {
	PIXEL,
	BAND
} InterleavingType;

static	uint16 compression = (uint16) -1;
static	int jpegcolormode = JPEGCOLORMODE_RGB;
static	int quality = 75;		/* JPEG quality */
static	uint16 predictor = 0;

static void swapBytesInScanline(void *, uint32, TIFFDataType);
static int guessSize(char *, long, TIFFDataType, off_t, uint32, int,
		     uint32 *, uint32 *);
static double correlation(void *, void *, uint32, TIFFDataType);
static void usage(void);
static	int processCompressOptions(char*);

//int main(int argc, char* argv[])
int saveIplImageAsTIFF(IplImage *img, const char * outfilename, char * compressionarg)
{
	uint32	width = 0, length = 0, linebytes, bufsize;
	uint32	nbands = 1;		    /* number of bands in input image*/
	off_t	hdr_size = 0;		    /* size of the header to skip */
	TIFFDataType dtype = TIFF_BYTE;
	int16	depth = 1;		    /* bytes per pixel in input image */
	int	swab = 0;		    /* byte swapping flag */
	InterleavingType interleaving = PIXEL;  /* interleaving type flag */
	uint32  rowsperstrip = (uint32) -1;
	uint16	photometric = PHOTOMETRIC_MINISBLACK;
	uint16	config = PLANARCONFIG_CONTIG;

	/* Define the FILLORDER: The logical order of bits within a byte
	FILLORDER_MSB2LSB = 1 : pixels with lower column values are stored in the higher-order bits of the byte
	FILLORDER_LSB2MSB = 2 : pixels with lower column values are stored in the lower-order bits of the byte - uncommon
	                        support for FillOrder=2 is not required in Baseline TIFF compliant readers*/
	uint16	fillorder = FILLORDER_MSB2LSB;
	TIFF	*out;

	uint32 row, col, band;
	int	c;
	unsigned char *buf = NULL, *buf1 = NULL;
	
	
	unsigned char *buffer = (unsigned char *)img->imageData;
	
	//while ((c = getopt(argc, argv, "c:r:H:w:l:b:d:LMp:si:o:h")) != -1) {
	//	switch (c) {
	//	case 'c':		/* compression scheme */
	if (!processCompressOptions(compressionarg))
		usage();
	
	//case 'r':		/* rows/strip */
	rowsperstrip = img->height; //atoi(optarg);
	//	case 'H':		/* size of input image file header */
	//		hdr_size = atoi(optarg);
	hdr_size = 0;
	//	case 'w':		/* input image width */
			width = img->width; //atoi(optarg);
	//	case 'l':		/* input image length */
			length = img->height; //atoi(optarg);
	//	case 'b':		/* number of bands in input image */
			nbands = img->nChannels; //atoi(optarg);
	//	case 'd':		/* type of samples in input image */
	switch(img->depth) {
	case IPL_DEPTH_8U:		//if (strncmp(optarg, "byte", 4) == 0)
		dtype = TIFF_BYTE;
		break;
	case IPL_DEPTH_16U:	//		else if (strncmp(optarg, "short", 5) == 0)
		dtype = TIFF_SHORT;
		break;
	//case IPL_DEPTH_32U:	//		else if  (strncmp(optarg, "long", 4) == 0)
	//	dtype = TIFF_LONG;
	//	break;
	case IPL_DEPTH_8S:	//		else if  (strncmp(optarg, "sbyte", 5) == 0)
		dtype = TIFF_SBYTE;
		break;
	case IPL_DEPTH_16S:	//		else if  (strncmp(optarg, "sshort", 6) == 0)
		dtype = TIFF_SSHORT;
		break;
	case IPL_DEPTH_32S:	//		else if  (strncmp(optarg, "slong", 5) == 0)
		dtype = TIFF_SLONG;
		break;
	case IPL_DEPTH_32F:	//		else if  (strncmp(optarg, "float", 5) == 0)
		dtype = TIFF_FLOAT;
		break;
	case IPL_DEPTH_64F:	//		else if  (strncmp(optarg, "double", 6) == 0)
		dtype = TIFF_DOUBLE;
		break;
	default:	//		else
		dtype = TIFF_BYTE;
		break;
	}
	depth = TIFFDataWidth(dtype);
	
	
	//fprintf(stderr, "%s %s:%d => TIFF depth=%d\n", __FILE__, __func__, __LINE__, depth);
	
	
	//	case 'L':		/* input has lsb-to-msb fillorder */
	//		fillorder = FILLORDER_LSB2MSB;
	//	case 'M':		/* input has msb-to-lsb fillorder */
	//		fillorder = FILLORDER_MSB2LSB;
	//		break;
	//	case 'p':		/* photometric interpretation */
	//		if (strncmp(optarg, "miniswhite", 10) == 0)
	//			photometric = PHOTOMETRIC_MINISWHITE;
	//		else if (strncmp(optarg, "rgb", 3) == 0)
	if(img->nChannels > 1)
				photometric = PHOTOMETRIC_RGB;
	else //if (strncmp(optarg, "minisblack", 10) == 0)
				photometric = PHOTOMETRIC_MINISBLACK;
	//		else if (strncmp(optarg, "cmyk", 4) == 0)
	//			photometric = PHOTOMETRIC_SEPARATED;
	//		else if (strncmp(optarg, "ycbcr", 5) == 0)
	//			photometric = PHOTOMETRIC_YCBCR;
	//		else if (strncmp(optarg, "cielab", 6) == 0)
	//			photometric = PHOTOMETRIC_CIELAB;
	//		else if (strncmp(optarg, "icclab", 6) == 0)
	//			photometric = PHOTOMETRIC_ICCLAB;
	//		else if (strncmp(optarg, "itulab", 6) == 0)
	//			photometric = PHOTOMETRIC_ITULAB;
	//		else
	//			photometric = PHOTOMETRIC_MINISBLACK;
	//		break;
	//	case 's':		/* do we need to swap bytes? */
	swab = 0;//		swab = 1;
	//		break;
	//	case 'i':		/* type of interleaving */
	//		if (strncmp(optarg, "pixel", 4) == 0)
	//			interleaving = PIXEL;
	//		else if  (strncmp(optarg, "band", 6) == 0)
	//			interleaving = BAND;
	//		else
				interleaving = PIXEL; //0;
	//		break;
	//	case 'o':
	//		outfilename = optarg;
	//		break;
	//	case 'h':
	//		usage();
	//	default:
	//		break;
	//	}
        
	
       hdr_size = 0;
       
	if (guessSize(img->imageData, img->widthStep * img->height,
		dtype, hdr_size, nbands, swab, &width, &length) < 0)
		return 1;

//fprintf(stderr, "[%s] %s:%d :dtype=%d, hdr_size=%d, nbands=%d, swab=%d, width=%d, length=%d\n",
//	__FILE__, __func__, __LINE__, 
//	dtype, (int)hdr_size, nbands, swab, width, length);
	
	out = TIFFOpen(outfilename, "w");
	if (out == NULL) {
//		fprintf(stderr, "%s: %s:%d : Cannot open file '%s' for output.\n",
//			__FILE__, __func__, __LINE__, outfilename);
		return (-1);
	}
	TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
	TIFFSetField(out, TIFFTAG_IMAGELENGTH, length);
	TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
	TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, nbands);
	TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, depth * 8);
	TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
	TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
	TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric);
	switch (dtype) {
	case TIFF_BYTE:
	case TIFF_SHORT:
	case TIFF_LONG:
		TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
		break;
	case TIFF_SBYTE:
	case TIFF_SSHORT:
	case TIFF_SLONG:
		TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_INT);
		break;
	case TIFF_FLOAT:
	case TIFF_DOUBLE:
		TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
		break;
	default:
		TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_VOID);
		break;
	}
	if (compression == (uint16) -1)
		compression = COMPRESSION_PACKBITS;
	TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
	switch (compression) {
	case COMPRESSION_JPEG:
		if (photometric == PHOTOMETRIC_RGB
		    && jpegcolormode == JPEGCOLORMODE_RGB)
			photometric = PHOTOMETRIC_YCBCR;
		TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
		TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
		break;
	case COMPRESSION_LZW:
	case COMPRESSION_DEFLATE:
		if (predictor != 0)
			TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
		break;
	}
	switch(interleaving) {
	case BAND:				/* band interleaved data */
		linebytes = width * depth;
		buf = (unsigned char *)_TIFFmalloc(linebytes);
		break;
	case PIXEL:				/* pixel interleaved data */
	default:
		linebytes = width * nbands * depth;
		break;
	}
	bufsize = width * nbands * depth;
	buf1 = (unsigned char *)_TIFFmalloc(bufsize);

	rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
	if (rowsperstrip > length) {
		rowsperstrip = length;
	}
	TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip );
	
	
//fprintf(stderr, "[%s] %s:%d :rowsperstrip=%d, bufsize=%d, linebytes=%d, nbands=%d, bufsize=%d, width=%d, length=%d\n",
//	__FILE__, __func__, __LINE__, 
//	rowsperstrip, bufsize, linebytes, nbands, bufsize, width, length);

	//lseek(fd, hdr_size, SEEK_SET);		/* Skip the file header */
	for (row = 0; row < length; row++) {
		switch(interleaving) {
		case BAND:			/* band interleaved data */
			for (band = 0; band < nbands; band++) {
				/*lseek(fd,
				      hdr_size + (length*band+row)*linebytes,
				      SEEK_SET);
				if (read(fd, buf, linebytes) < 0) {
					fprintf(stderr,
					"%s: %d: scanline %lu: Read error.\n",
					__func__, __LINE__, 
					(unsigned long) row);
				*/
				memcpy(buf, buffer + (length*band+row)*linebytes, linebytes);
//				fprintf(stderr,
//					"\r%s: %d: BAND scan line %lu...",
//					__func__, __LINE__, 
//					(unsigned long) row);
				if (swab)	/* Swap bytes if needed */
					swapBytesInScanline(buf, width, dtype);
				for (col = 0; col < width; col++)
					memcpy(buf1 + (col*nbands+band)*depth,
					       buf + col * depth, depth);
			}
			break;
		case PIXEL:			/* pixel interleaved data */
		default:
			/*if (read(fd, buf1, bufsize) < 0) {
				fprintf(stderr,
					"%s:%d: scanline %lu: Read error.\n",
					__func__, __LINE__,
					(unsigned long) row);
				break;
			}*/
			memcpy(buf1, buffer + row*img->widthStep, bufsize);
			if (swab)		/* Swap bytes if needed */
				swapBytesInScanline(buf1, width, dtype);
			break;
		}
				
		if (TIFFWriteScanline(out, buf1, row, 0) < 0) {
//			fprintf(stderr,	"%s:%d : %s: scanline %lu: Write error.\n",
//				__func__, __LINE__, outfilename, (unsigned long) row);
			break;
		}
	}
	if (buf)
		_TIFFfree(buf);
	if (buf1)
		_TIFFfree(buf1);
	TIFFClose(out);
	return (0);
}

static void
swapBytesInScanline(void *buf, uint32 width, TIFFDataType dtype)
{
	switch (dtype) {
		case TIFF_SHORT:
		case TIFF_SSHORT:
			TIFFSwabArrayOfShort((uint16*)buf,
                                             (unsigned long)width);
			break;
		case TIFF_LONG:
		case TIFF_SLONG:
			TIFFSwabArrayOfLong((uint32*)buf,
                                            (unsigned long)width);
			break;
		/* case TIFF_FLOAT: */	/* FIXME */
		case TIFF_DOUBLE:
			TIFFSwabArrayOfDouble((double*)buf,
                                              (unsigned long)width);
			break;
		default:
			break;
	}
}

static int
guessSize(char * buffer, long buffer_size, 
	TIFFDataType dtype, off_t hdr_size, uint32 nbands,
	  int swab, uint32 *width, uint32 *length)
{
	const float longt = 40.0;    /* maximum possible height/width ratio */
	char	    *buf1, *buf2;
	struct stat filestat;
	uint32	    w, h, scanlinesize, imagesize;
	uint32	    depth = TIFFDataWidth(dtype);
	float	    cor_coef = 0, tmp;


	imagesize = buffer_size //(filestat.st_size - hdr_size)
			/ nbands / depth;

	if (*width != 0 && *length == 0) {
		fprintf(stderr,	"Image height is not specified.\n");

		*length = imagesize / *width;
		
		fprintf(stderr, "Height is guessed as %lu.\n",
			(unsigned long)*length);

		return 1;
	} else if (*width == 0 && *length != 0) {
		fprintf(stderr, "Image width is not specified.\n");

		*width = imagesize / *length;
		
		fprintf(stderr,	"Width is guessed as %lu.\n",
			(unsigned long)*width);

		return 1;
	} else if (*width == 0 && *length == 0) {
		fprintf(stderr,	"Image width and height are not specified.\n");

		for (w = (uint32) sqrt(imagesize / longt);
		     w < sqrt(imagesize * longt);
		     w++) {
			if (imagesize % w == 0) {
				scanlinesize = w * depth;
				buf1 = (char *)_TIFFmalloc(scanlinesize);
				buf2 = (char *)_TIFFmalloc(scanlinesize);
				h = imagesize / w;
				
				/*
				lseek(fd, hdr_size + (int)(h/2)*scanlinesize,
				      SEEK_SET);
				read(fd, buf1, scanlinesize);
				read(fd, buf2, scanlinesize);
				*/
				memcpy(buf1, buffer + (int)(h/2)*scanlinesize, scanlinesize);
				memcpy(buf2, buffer + ((int)(h/2) + 1)*scanlinesize, scanlinesize);
				
				if (swab) {
					swapBytesInScanline(buf1, w, dtype);
					swapBytesInScanline(buf2, w, dtype);
				}
				tmp = (float) fabs(correlation(buf1, buf2,
							       w, dtype));
				if (tmp > cor_coef) {
					cor_coef = tmp;
					*width = w, *length = h;
				}

				_TIFFfree(buf1);
				_TIFFfree(buf2);
			}
		}

		fprintf(stderr,
			"Width is guessed as %lu, height is guessed as %lu.\n",
			(unsigned long)*width, (unsigned long)*length);

		return 1;
	} 

	return 1;
}



/* Calculate correlation coefficient between two numeric vectors */
static double
correlation(void *buf1, void *buf2, uint32 n_elem, TIFFDataType dtype)
{
	double	X, Y, M1 = 0.0, M2 = 0.0, D1 = 0.0, D2 = 0.0, K = 0.0;
	uint32	i;

	switch (dtype) {
		case TIFF_BYTE:
		default:
                        for (i = 0; i < n_elem; i++) {
				X = ((unsigned char *)buf1)[i];
				Y = ((unsigned char *)buf2)[i];
				M1 += X, M2 += Y;
				D1 += X * X, D2 += Y * Y;
				K += X * Y;
                        }
			break;
		case TIFF_SBYTE:
                        for (i = 0; i < n_elem; i++) {
				X = ((signed char *)buf1)[i];
				Y = ((signed char *)buf2)[i];
				M1 += X, M2 += Y;
				D1 += X * X, D2 += Y * Y;
				K += X * Y;
                        }
			break;
		case TIFF_SHORT:
                        for (i = 0; i < n_elem; i++) {
				X = ((uint16 *)buf1)[i];
				Y = ((uint16 *)buf2)[i];
				M1 += X, M2 += Y;
				D1 += X * X, D2 += Y * Y;
				K += X * Y;
                        }
			break;
		case TIFF_SSHORT:
                        for (i = 0; i < n_elem; i++) {
				X = ((int16 *)buf1)[i];
				Y = ((int16 *)buf2)[i];
				M1 += X, M2 += Y;
				D1 += X * X, D2 += Y * Y;
				K += X * Y;
                        }
			break;
		case TIFF_LONG:
                        for (i = 0; i < n_elem; i++) {
				X = ((uint32 *)buf1)[i];
				Y = ((uint32 *)buf2)[i];
				M1 += X, M2 += Y;
				D1 += X * X, D2 += Y * Y;
				K += X * Y;
                        }
			break;
		case TIFF_SLONG:
                        for (i = 0; i < n_elem; i++) {
				X = ((int32 *)buf1)[i];
				Y = ((int32 *)buf2)[i];
				M1 += X, M2 += Y;
				D1 += X * X, D2 += Y * Y;
				K += X * Y;
                        }
			break;
		case TIFF_FLOAT:
                        for (i = 0; i < n_elem; i++) {
				X = ((float *)buf1)[i];
				Y = ((float *)buf2)[i];
				M1 += X, M2 += Y;
				D1 += X * X, D2 += Y * Y;
				K += X * Y;
                        }
			break;
		case TIFF_DOUBLE:
                        for (i = 0; i < n_elem; i++) {
				X = ((double *)buf1)[i];
				Y = ((double *)buf2)[i];
				M1 += X, M2 += Y;
				D1 += X * X, D2 += Y * Y;
				K += X * Y;
                        }
			break;
	}

	M1 /= n_elem;
	M2 /= n_elem;
	D1 -= M1 * M1 * n_elem;
	D2 -= M2 * M2 * n_elem;
	K = (K - M1 * M2 * n_elem) / sqrt(D1 * D2);

	return K;
}

// in none, packbits,jpeg,lzw,zip

static int
processCompressOptions(char* opt)
{
	if (strcmp(opt, "none") == 0)
		compression = COMPRESSION_NONE;
	else if (strcmp(opt, "packbits") == 0)
		compression = COMPRESSION_PACKBITS;
	else if (strncmp(opt, "jpeg", 4) == 0) {
		char* cp = strchr(opt, ':');

                compression = COMPRESSION_JPEG;
                while( cp )
                {
                    if (isdigit((int)cp[1]))
			quality = atoi(cp+1);
                    else if (cp[1] == 'r' )
			jpegcolormode = JPEGCOLORMODE_RAW;
                    else
                        usage();

                    cp = strchr(cp+1,':');
                }
	} else if (strncmp(opt, "lzw", 3) == 0) {
		char* cp = strchr(opt, ':');
		if (cp)
			predictor = atoi(cp+1);
		compression = COMPRESSION_LZW;
	} else if (strncmp(opt, "zip", 3) == 0) {
		char* cp = strchr(opt, ':');
		if (cp)
			predictor = atoi(cp+1);
		compression = COMPRESSION_DEFLATE;
	} else
		return (0);
	return (1);
}

static char* stuff[] = {
"raw2tiff --- tool for converting raw byte sequences in TIFF images",
"usage: raw2tiff [options] input.raw output.tif",
"where options are:",
" -L		input data has LSB2MSB bit order (default)",
" -M		input data has MSB2LSB bit order",
" -r #		make each strip have no more than # rows",
" -H #		size of input image file header in bytes (0 by default)",
" -w #		width of input image in pixels",
" -l #		length of input image in lines",
" -b #		number of bands in input image (1 by default)",
"",
" -d data_type	type of samples in input image",
"where data_type may be:",
" byte		8-bit unsigned integer (default)",
" short		16-bit unsigned integer",
" long		32-bit unsigned integer",
" sbyte		8-bit signed integer",
" sshort		16-bit signed integer",
" slong		32-bit signed integer",
" float		32-bit IEEE floating point",
" double		64-bit IEEE floating point",
"",
" -p photo	photometric interpretation (color space) of the input image",
"where photo may be:",
" miniswhite	white color represented with 0 value",
" minisblack	black color represented with 0 value (default)",
" rgb		image has RGB color model",
" cmyk		image has CMYK (separated) color model",
" ycbcr		image has YCbCr color model",
" cielab		image has CIE L*a*b color model",
" icclab		image has ICC L*a*b color model",
" itulab		image has ITU L*a*b color model",
"",
" -s		swap bytes fetched from input file",
"",
" -i config	type of samples interleaving in input image",
"where config may be:",
" pixel		pixel interleaved data (default)",
" band		band interleaved data",
"",
" -c lzw[:opts]	compress output with Lempel-Ziv & Welch encoding",
" -c zip[:opts]	compress output with deflate encoding",
" -c jpeg[:opts]	compress output with JPEG encoding",
" -c packbits	compress output with packbits encoding",
" -c none	use no compression algorithm on output",
"",
"JPEG options:",
" #		set compression quality level (0-100, default 75)",
" r		output color image as RGB rather than YCbCr",
"For example, -c jpeg:r:50 to get JPEG-encoded RGB data with 50% comp. quality",
"",
"LZW and deflate options:",
" #		set predictor value",
"For example, -c lzw:2 to get LZW-encoded data with horizontal differencing",
" -o out.tif	write output to out.tif",
" -h		this help message",
NULL
};

static void
usage(void)
{
	char buf[BUFSIZ];
	int i;

	setbuf(stderr, buf);
        fprintf(stderr, "%s\n\n", TIFFGetVersion());
	for (i = 0; stuff[i] != NULL; i++)
		fprintf(stderr, "%s\n", stuff[i]);
	exit(-1);
}













//************************************
// Method:		findAlignment
// FullName:	CropImage::findAlignment
// Access:		public 
// Returns:		void
// Parameter:	IplImage * image
// Description: find alignment of image, rotate if nose = right
//************************************
void CropImage::findAlignment(IplImage* image)
{
	IplImage *temp = cvCloneImage(image);
	cvSetImageROI(temp,cvRect(0,(image->height/2)-200,370,400));
	int check1=0, check2=0;
	IplImage* dst = cvCreateImage( cvGetSize(temp), 8, 1 );
	IplImage* color_dst = cvCreateImage( cvGetSize(temp), 8, 3 );
	cvZero(dst);
	CvMemStorage* storage = cvCreateMemStorage(0);
	CvSeq* lines = 0;
	int i;
	int countNonVerticalLines=0;
	//threshold ROI
	for (int i=-200; i<200; i++)
		{
			for (int j=0; j<370; j++)
			{
				Pixel pix = ImageUtils::getPixel(temp,j,i+(image->height/2),temp->nChannels);
				if (pix.getValue() < 10)
					ImageUtils::setPixel(temp,Pixel(cvPoint(j,i+(image->height/2)),0,0,0,0,3));
				else
					ImageUtils::setPixel(temp,Pixel(cvPoint(j,i+(image->height/2)),255,255,255,255,3));
			}
		}
	
	

	//get rid of "snow"
	cvErode(temp,temp,0,3);
	cvDilate(temp,temp,0,6);
	cvErode(temp,temp,0,3);
	for (int i=0; i<10; i++)
	{
		cvSmooth(temp,temp,CV_GAUSSIAN,19);
		cvThreshold(temp,temp,30,255,0);
	}

	if (Init::getDebug())
	{
		cvNamedWindow("Image Nose", 0);
		cvShowImage("Image Nose", temp);
		cvResizeWindow( "Image Nose", 370,  400 );
		cvMoveWindow("Image Nose", 0, 0);
		/*
		cvWaitKey(0);
				cvDestroyAllWindows();*/
		
	}

	//find edges for better results
	cvSobel( temp, dst, 1,0, 3 );
	cvCvtColor( dst, color_dst, CV_GRAY2BGR );

	//find lines
	lines = cvHoughLines2( dst, storage, CV_HOUGH_STANDARD, 1, CV_PI/4, 20, 0, 0 );


	for( i = 0; i < MIN(lines->total,100); i++ )
	{
		float* line = (float*)cvGetSeqElem(lines,i);
		float rho = line[0];
		float theta = line[1];
		CvPoint pt1, pt2;
		double a = cos(theta), b = sin(theta);
		double x0 = a*rho, y0 = b*rho;
		pt1.x = cvRound(x0 + 1000*(-b));
		pt1.y = cvRound(y0 + 1000*(a));
		pt2.x = cvRound(x0 - 1000*(-b));
		pt2.y = cvRound(y0 - 1000*(a));
		cvLine( color_dst, pt1, pt2, CV_RGB(255,0,0), 3, 8 );
		if(pt1.x!=pt2.x)
			countNonVerticalLines++;
	}

	//for debugging: draw line
	if (Init::getDebug())
	{
		cvNamedWindow("Image Nose Lines", 0);
		cvShowImage("Image Nose Lines", color_dst);
		cvResizeWindow( "Image Nose Lines", 370,  400 );
		cvMoveWindow("Image Nose Lines", 400,0 );
		cvWaitKey(0);
		cvDestroyAllWindows();
	}

	cvResetImageROI(image);
	cvReleaseImage(&temp);

	//if image has to be rotated, cvHoughLines only returned one to two lines, else, there are more
	if (countNonVerticalLines > 0)
	{
		Init::setRotateImage(false);
		if(Init::getDebug())
			Debug::message(">>>  Alignment: Left\t\t<<<",Debug::VERBOSE);
	}
	else
	{
		Init::setRotateImage(true);
		if(Init::getDebug())
			Debug::message(">>>  Alignment: Right\t\t<<<",Debug::VERBOSE);
	}
	
	cvReleaseImage(&dst);
	cvReleaseImage(&color_dst);

}


void CropImage::rotateImage(IplImage* &image)
{
	CvMat *matrix=cvCreateMat(2, 3, CV_32FC1);
	IplImage *temp=cvCloneImage(image);
	//initiate rotation matrix
	cv2DRotationMatrix( cvPoint2D32f(image->width/2,image->height/2), 180, 1, matrix );
	
	//rotate image
	cvWarpAffine( image, temp, matrix, CV_WARP_FILL_OUTLIERS,cvScalarAll(0));
	cvReleaseImage(&image);
	image=cvCloneImage(temp);
	cvReleaseImage(&temp);
}


//************************************
// Method:		crop
// FullName:	CropImage::crop
// Access:		public 
// Returns:		void
// Parameter:	IplImage * image
// Parameter:	int type
// Parameter:	int ammount
// Description: main crop method
//************************************
void CropImage::findCutLines(IplImage *image, int type, int ammount)
{
	//due to separators in trilens images, make a difference between tri- and telelens
	if (type == 0)
		CropImage::findEdgeTele(image, ammount);
	else
		CropImage::findEdgeTri(image, ammount);

}


//************************************
// Method:		findEdgeTele
// FullName:	CropImage::findEdgeTele
// Access:		private static 
// Returns:		void
// Parameter:	IplImage * image
// Parameter:	int ammount
// Description:	find image edges for tele-images
//************************************
void CropImage::findEdgeTele(IplImage *image, int ammount)
{
	//CvPoint topleft=cvPoint(0,0), lowerright=cvPoint(0,0);
	int check1 = 1, check2 = 1, check3=1, count = 0;
	IplImage *temp=cvCloneImage(image);
	cvThreshold(temp,temp,5,255,CV_THRESH_BINARY);
	cvSetImageROI(temp,cvRect(0,0,temp->width,500));

	//get rid of snow
	cvErode(temp,temp,0,3);
	cvDilate(temp,temp,0,6);
	cvErode(temp,temp,0,3);

	cvSetImageROI(temp,cvRect(0,9800,temp->width,temp->height-9800));

	cvErode(temp,temp,0,3);
	cvDilate(temp,temp,0,6);
	cvErode(temp,temp,0,3);

	//at two points (imagewidth/8 and imagewidth*7/8) run from y=0 to the center of the image, until there is no more black border on both points
	while (check1)
	{
		if (ImageUtils::getPixelValue(temp,temp->width/8,count)==255 && ImageUtils::getPixelValue(temp,7*temp->width/8,count)==255)
		{
			Init::setTopleft(-1,count+20);
			check1=0;
		}
				
		count++;
	}

	count=image->height-1;
	//same like above, from x=imageheight
	while (check2)
	{
		if (ImageUtils::getPixelValue(temp,temp->width/2,count)==255 && ImageUtils::getPixelValue(temp,7*temp->width/8,count)==255)
		{
			Init::setLowerright(-1,count-20);
			check2=0;
		}

		count--;
	}



	//same like above, from the left at y=found value
	for (int i=temp->width/8; i>0; i--)
	{
		if (check3 && ImageUtils::getPixelValue(temp,i,Init::getTopleft().y)==0)
		{
			Init::setTopleft(i+100,-1);
			check3=0;
		}
		else if (check3 && ImageUtils::getPixelValue(temp,i,9800)==0)
		{
			Init::setTopleft(i+100,-1);
			check3=0;
		}
	}


	//same like above, from the right at y=found value
	check3=1;
	for (int i=7*(temp->width/8); i<temp->width; i++)
	{
		if (check3 && ImageUtils::getPixelValue(temp,i,Init::getTopleft().y)==0)
		{
			check3=0;
			Init::setLowerright(i-100,-1);
		}
		else if (check3 && ImageUtils::getPixelValue(temp,i,Init::getLowerright().y)==0)
		{
			check3=0;
			Init::setLowerright(i-100,-1);
		}
	}
	cvResetImageROI(temp);

	//debuging
	if (Init::getDebug())
	{
		IplImage *test = cvCreateImage(cvSize(temp->width,temp->height),8,3);
		cvConvertImage( temp, test, 0 );

		cvLine(test, Init::getTopleft(),cvPoint(Init::getTopleft().x,Init::getLowerright().y), cvScalar(0,0,255,0), 20, 8, 0);
		cvLine(test, Init::getTopleft(),cvPoint(Init::getLowerright().x,Init::getTopleft().y), cvScalar(0,0,255,0), 20, 8, 0);
		cvLine(test, Init::getLowerright(),cvPoint(Init::getTopleft().x,Init::getLowerright().y), cvScalar(0,0,255,0), 20, 8, 0);
		cvLine(test, Init::getLowerright(),cvPoint(Init::getLowerright().x,Init::getTopleft().y), cvScalar(0,0,255,0), 20, 8, 0);

		//cvSetImageROI(image,cvRect(topleft.x,topleft.y,(lowerright.x-topleft.x),(lowerright.y-topleft.y)));

		cvNamedWindow("Crop Lines", 0);
		cvShowImage("Crop Lines", test);
		cvResizeWindow( "Crop Lines", test->width/14,test->height/14 );
		cvMoveWindow("Crop Lines", 0, 0);

		cvReleaseImage(&test);
	}

	cvReleaseImage(&temp);
}


//************************************
// Method:    findEdgeTri
// FullName:  CropImage::findEdgeTri
// Access:    private static 
// Returns:   void
// Parameter: IplImage * image
// Parameter: int ammount
// Description:	find image edges for trilens-images
//************************************
void CropImage::findEdgeTri(IplImage *image, int ammount)
{
	
	//CvPoint topleft=cvPoint(0,0), lowerright=cvPoint(0,0);

	int check1 = 1, check2 = 1, check3=1, count = 0, sw=0, key=255;
	int x1=600;
	IplImage *temp=cvCloneImage(image);

	cvSmooth(temp,temp,CV_GAUSSIAN,19);
	cvThreshold(temp,temp,10,255,0);


	//get rid of snow in relevant areas
	cvSetImageROI(temp,cvRect(550,0,100,temp->height));
	cvErode(temp,temp,0,5);
	cvDilate(temp,temp,0,15);
	cvErode(temp,temp,0,10);

	cvSetImageROI(temp,cvRect(3450,0,100,temp->height));
	cvErode(temp,temp,0,5);
	cvDilate(temp,temp,0,15);
	cvErode(temp,temp,0,10);

	cvSetImageROI(temp,cvRect(0,0,4500,550));
	cvErode(temp,temp,0,5);
	cvDilate(temp,temp,0,15);
	cvErode(temp,temp,0,10);

	cvSetImageROI(temp,cvRect(0,9800,4500,temp->height-9800));
	cvErode(temp,temp,0,5);
	cvDilate(temp,temp,0,15);
	cvErode(temp,temp,0,10);
	

	cvResetImageROI(temp);


	/*detecting the y-values for all three partial images
	  due to the position of the search, "key" will be switched between 0 and 255
	  "x1" will be set to "1000" at the last step because of the cutout at the codeblock*/
	while (check1 && count<temp->height)
	{
		if (ImageUtils::getPixelValue(temp,x1,count)==key && ImageUtils::getPixelValue(temp,3500,count)==key)
		{
			switch(sw)
			{
				//first y-value for top image
			case 0:
				Init::setTopleft(-1,count+50);
				count+=3000;
				sw++;
				key=0;
				break;
				//second y-value for top image
			case 1:
				Init::setYParts(0,count-50);
				sw++;
				key=255;
				break;
				//first y-value for second image
			case 2:
				Init::setYParts(1,count+50);
				sw++;
				key=0;
				break;
			case 3:
				sw++;
				key=255;
				break;
			case 4:
				Init::setYParts(3,count+50);
				check1=0;
				break;			
			}
		}

		count++;
	}
	Init::setYParts(2,Init::getYPart(1)+(Init::getYPart(0)-Init::getTopleft().y)-50);
	//Init::setYParts(3,Init::getYPart(2)+(Init::getYPart(1)-Init::getYPart(0))+50);
	Init::setLowerright(-1,Init::getYPart(3)+(Init::getYPart(0)-Init::getTopleft().y)-50);

	//get left x-value
	for (int i=0; i<1000; i++)
	{
		if (ImageUtils::getPixelValue(temp,i,Init::getTopleft().y)==255 && ImageUtils::getPixelValue(temp,i,temp->height-1000)==255)
		{	
			Init::setTopleft(i+50,-1);
			i=1000;	
		}
	}

	//get right x-value
	

	for (int i=3800; i>3000; i--)
	{
		if (ImageUtils::getPixelValue(temp,i,Init::getTopleft().y)==255 && ImageUtils::getPixelValue(temp,i,Init::getLowerright().y)==255)
		{
			Init::setLowerright(i-50,-1);
			i=2900;
		}
	}

	//get Offset
	if (ammount > 1)
	{
		for (int i=Init::getLowerright().x+150; i<Init::getLowerright().x+900; i++)
		{
			if (ImageUtils::getPixelValue(temp,i,Init::getTopleft().y)==255 && ImageUtils::getPixelValue(temp,i,temp->height-1000)==255)
			{
				Init::setOffset(i-Init::getTopleft().x+50);
				i=Init::getLowerright().x+905;
			}
		}
	} else {
		Init::setOffset(0);
	}
	cvReleaseImage(&temp);

	//debug
	if (0)
	{
		IplImage *temp = cvCreateImage(cvSize(image->width,image->height),8,1);
		temp=cvCloneImage(image);
		//temp=cvCloneImage(image);
		
		for (int i=0; i<ammount; i++)
				{
					cvLine(temp, cvPoint((i*Init::getOffset())+Init::getTopleft().x,Init::getTopleft().y),cvPoint((i*Init::getOffset())+Init::getTopleft().x,Init::getLowerright().y), cvScalar(0,0,255,0), 20, 8, 0);
					cvLine(temp, cvPoint((i*Init::getOffset())+Init::getTopleft().x,Init::getTopleft().y),cvPoint((i*Init::getOffset())+Init::getLowerright().x,Init::getTopleft().y), cvScalar(0,0,255,0), 20, 8, 0);
					cvLine(temp, cvPoint((i*Init::getOffset())+Init::getLowerright().x,Init::getLowerright().y),cvPoint((i*Init::getOffset())+Init::getTopleft().x,Init::getLowerright().y), cvScalar(0,0,255,0), 20, 8, 0);
					cvLine(temp, cvPoint((i*Init::getOffset())+Init::getLowerright().x,Init::getLowerright().y),cvPoint((i*Init::getOffset())+Init::getLowerright().x,Init::getTopleft().y), cvScalar(0,0,255,0), 20, 8, 0);
					cvLine(temp, cvPoint((i*Init::getOffset())+Init::getTopleft().x,Init::getYPart(0)),cvPoint((i*Init::getOffset())+Init::getLowerright().x,Init::getYPart(0)), cvScalar(0,0,255,0), 20, CV_AA, 0);
					cvLine(temp, cvPoint((i*Init::getOffset())+Init::getTopleft().x,Init::getYPart(1)),cvPoint((i*Init::getOffset())+Init::getLowerright().x,Init::getYPart(1)), cvScalar(0,0,255,0), 20, CV_AA, 0);
					cvLine(temp, cvPoint((i*Init::getOffset())+Init::getTopleft().x,Init::getYPart(2)),cvPoint((i*Init::getOffset())+Init::getLowerright().x,Init::getYPart(2)), cvScalar(0,0,255,0), 20, CV_AA, 0);
					cvLine(temp, cvPoint((i*Init::getOffset())+Init::getTopleft().x,Init::getYPart(3)),cvPoint((i*Init::getOffset())+Init::getLowerright().x,Init::getYPart(3)), cvScalar(0,0,255,0), 20, CV_AA, 0);
			
				}
		
		//cvSetImageROI(image,cvRect(topleft.x,topleft.y,(lowerright.x-topleft.x),(lowerright.y-topleft.y)));
		cvNamedWindow("Crop Lines", 0);
		cvShowImage("Crop Lines", temp);
		cvResizeWindow( "Crop Lines", image->width/14,image->height/14 );
		cvMoveWindow("Crop Lines", 0, 0);
		cvWaitKey(0);
		cvReleaseImage(&temp);
	}
}



void CropImage::getLeftXValue(IplImage *image)
{
	IplImage *temp=cvCloneImage(image);
	cvThreshold(temp,temp,5,255,CV_THRESH_BINARY);

	cvSetImageROI(temp,cvRect(0,0,1000,Init::getTopleft().y+200));
	cvErode(temp,temp,0,3); 
	cvDilate(temp,temp,0,16);
	cvErode(temp,temp,0,13);

	cvSetImageROI(temp,cvRect(0,temp->height-1500,1000,1499));
	cvErode(temp,temp,0,3);
	cvDilate(temp,temp,0,16);
	cvErode(temp,temp,0,13);
	cvResetImageROI(temp);

	//get left x-value
	for (int i=0; i<1000; i++)
	{
		if (ImageUtils::getPixelValue(temp,i,Init::getTopleft().y)==255 && ImageUtils::getPixelValue(temp,i,temp->height-1000)==255)
		{	
			Init::setLowerright((i+50)+(Init::getLowerright().x-Init::getTopleft().x),-1);
			Init::setTopleft(i+50,-1);
			i=1000;	
		}
	}
	cvReleaseImage(&temp);
}

/*
void CropImage::cutImage(IplImage *image,int type, std::string filename, int ammount)
{
	if (type==0)
		cutImageTele(image, filename, ammount);
	else
		cutImageTri(image, filename, ammount);
}*/


void CropImage::cutImage(IplImage *image, int type, std::string filename, int part, int ammount)
{
	CvPoint topleft = Init::getTopleft();
	CvPoint lowerright = Init::getLowerright();
	int offset = Init::getOffset();
	int counter=-1;
	int width = lowerright.x-topleft.x;
	int height = lowerright.y-topleft.y;
	
	std::stringstream out;
	out<<Init::getFilenameAppend()<<filename<<"_";
	if(ammount-part<10 && ammount>1)
		out<<"0"<<ammount-part;
	else if (ammount>1)
		out<<ammount-part;

	filename=out.str();

	/*for (int i=0; i<ammount; i++)
	{*/
		if (type == 0)
		{
			if (ammount!=1)
				counter=part;
			CropImage::saveImage(image,cvRect((part*offset)+topleft.x,topleft.y,width,height),filename,counter,"","TE");
		} else {
			CropImage::saveImage(image,cvRect((part*offset)+topleft.x,topleft.y,width,Init::getYPart(0)-topleft.y),filename,(part*3)+1,"R","TR");
			CropImage::saveImage(image,cvRect((part*offset)+topleft.x,Init::getYPart(1),width,Init::getYPart(2)-Init::getYPart(1)),filename,(part*3)+2,"N","TR");
			CropImage::saveImage(image,cvRect((part*offset)+topleft.x,Init::getYPart(3),width,lowerright.y-Init::getYPart(3)),filename,(part*3)+3,"L","TR");
		}
	//}
	cvWaitKey(0);
	cvDestroyAllWindows();

}

void CropImage::saveImage(IplImage * image,CvRect area, std::string filename,int counter, std::string part, std::string type)
{
	//cvSetImageROI(image, area);
	IplImage *temp = cvCreateImage(cvSize(area.width,area.height), image->depth, 1);
	

	for (int j=area.x; j<area.x+area.width; j++)
	{
		for (int i=area.y; i<area.y+area.height; i++)
		{
			(((uchar*)(temp->imageData + temp->widthStep*(i-area.y))))[(area.width-(j-area.x)-1) * temp->nChannels] = (((uchar*)(image->imageData + image->widthStep*((area.y+area.height-(i-area.y))))))[j * image->nChannels];
			/*Pixel pix = ImageUtils::getPixel(image,i,j,image->nChannels);
			pix.y=j-area.y;
			pix.x=i-area.x;
			ImageUtils::setPixel(temp,pix);*/
		}
	}


	std::string st(Init::getPath());
	//stringstream for appending int
	std::stringstream out;

	//replace "\" with "/"
	for (int i=0; i<st.size(); i++)
	{
		if (st[i]=='\\')
			st[i]='/';
	}
	//appending all the stuff for a valid path
	st+=Init::getImageDir();
	st+="/";


	filename+=part;
	filename+=type;

	st+=filename;
	//st+="image";
	/*if (counter != -1)
	{
		st+="(";
		out<<counter;
		st+=out.str();
		st+=")";
	}*/
	st+=".tif";
	// saveIplImageAsTIFF(temp,st.c_str(),"none");
	// cvSaveImage(st.c_str(),image);
	cvSaveImage(st.c_str(),temp);
	
	if (Init::getDebug() && counter != -1)
	{
		//int temp2 = ((counter-1) / 5);
		//int width = temp2*150+900;

		std::string guiName = "Image Part ";
		if (counter != -1)
			guiName+=part;
		cvNamedWindow(guiName.c_str(), 0);
		cvResizeWindow( guiName.c_str(), area.width/22,area.height/22 );
		cvMoveWindow(guiName.c_str(), 900, ((counter-1)%3)*175);
		//cvMoveWindow(guiName.c_str(),0,0);
		cvShowImage(guiName.c_str(), temp);/*
		
				cvWaitKey(0);
				cvDestroyWindow(guiName.c_str());*/
		
	} else if (Init::getDebug() && counter == -1)
	{
		cvNamedWindow("Image Part 1", 0);
		cvResizeWindow("Image Part 1", area.width/14,area.height/14 );
		cvMoveWindow("Image Part 1", image->width/14+100, 0);
		cvShowImage("Image Part 1", temp);
	}
	
	cvReleaseImage(&temp);
	cvResetImageROI(image);
	
}
